import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'

import Article from '@/pages/Home/Article.vue'
import Overview from '@/pages/Home/Overview.vue'
import Publish from '@/pages/Home/Publish.vue'

// 路由配置
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  // history: createWebHashHistory(),
  routes: [
    { 
      path: '/login',
      component: () => import('@/pages/Login.vue'),
    },
    {
      path: '/',
      component: () => import('@/pages/Home/index.vue'),
      redirect: '/overview',
      children: [
        {
          path: '/overview',
          component: Overview,
        },
        {
          path: '/article',
          component: Article,
        },
        {
          name: 'publish',
          path: '/publish/:id?',
          component: Publish,
        },
        {
          path: '/individual',
          component: () => import('@/pages/Home/Individual.vue'),
        }
      ]
    }
  ],
})

// 路由拦截器
router.beforeEach((to, from, next) => {
  // 判断访问一些页面的时候是否登录
  if (to.path === '/login') {
    next()
  } else {
    if (useUserStore().userInfo?.token) {
      next()
    } else {
      ElMessage({
        message: '请先登录',
        type: 'warning',
      })
      next('/login')
    }
  }
})

export default router
